/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

/**
 * Web Page Profile
 */

wsshWebDomainProfile.prototype.clone = function()
{
    var thisClone = new wsshWebDomainProfile(this.domain);
    thisClone.signature = this.signature;
    thisClone.checksum = this.checksum;
    thisClone.hidden = this.hidden;

    if (this.pages)
    {
        for(var key in this.pages)
        {
            if (!this.pages[key])
                continue;

            thisClone.pages.push(this.pages[key].clone());
        }
    }

    return thisClone;
}

/**
 * Web Page Profile
 */

wsshWebPageProfile.prototype.extractUrl = function(elem)
{
    if (this.elementUrlAttribute)
    {
        try
        {
            if (this.elementUrlAttribute == "style:background-image")
            {
                if (!elem["style"] || !elem.style.backgroundImage)
                    return null;

                var backgroundImageUrl = elem.style.backgroundImage;
                if (backgroundImageUrl.indexOf("url(") != 0)
                    return null;

                return backgroundImageUrl.substring(4, backgroundImageUrl.length-5);
            }
            else
            {
                return elem.getAttribute(this.elementUrlAttribute);
            }
        }
        catch(e)
        {
            return null;
        }
    }

    if (!this.tagToUrl[this.elementTag])
        return null;

    return elem[this.tagToUrl[this.elementTag]];
}

wsshWebPageProfile.prototype.isJavaScriptTemplate = function()
{
    return this.elementTemplate && (0 == this.elementTemplate.indexOf("javascript:"));
}

wsshWebPageProfile.prototype.createURLFromTemplate = function(originalURL)
{
    if (!this.elementTemplate)
        throw "Page has no template!";

    var values = new Array();
    for (var k = 1; k <= 9; ++k)
    {
        var x = RegExp["$" + k];
        if (!x)
            break;

        values.push(x);
    }

    // replace parameters
    var elementTemplate = this.elementTemplate;
    for (var z = 1; z <= values.length; ++z)
    {
        elementTemplate = elementTemplate.replace(new RegExp("\\$"+z+"\\$", "g"), values[z-1]);
    }

    if (this.isJavaScriptTemplate())
        elementTemplate = elementTemplate.replace(/\$originalURL\$/g, originalURL);

    return elementTemplate;
}

wsshWebPageProfile.prototype.clone = function()
{
    var thisClone = new wsshWebPageProfile();

    if (this.pattern) thisClone.pattern = new RegExp(this.pattern.source);
    thisClone.supported = this.supported;
    thisClone.disabled = this.disabled;
    thisClone.browser = this.browser;
    thisClone.elementTag = this.elementTag;
    thisClone.elementUrlAttribute = this.elementUrlAttribute;
    if (this.elementPattern) thisClone.elementPattern = new RegExp(this.elementPattern.source);
    thisClone.elementTemplate = this.elementTemplate;

    return thisClone;
}
